package com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.share;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.bumptech.glide.Glide;
import com.coffeeloversupportlibrary.R;
import com.coffeeloversupportlibrary.coffeelover.uicompont.AnimationUtils;
import com.coffeeloversupportlibrary.coffeelover.uicompont.MyDialog;
import com.coffeeloversupportlibrary.core.base.BaseActivity;

import com.coffeeloversupportlibrary.databinding.ShareActivityBinding;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.mylhyl.circledialog.BaseCircleDialog;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.res.drawable.CircleDrawable;
import com.mylhyl.circledialog.res.values.CircleColor;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



/**
 * @author puyv
 * @createTime 2021/11/24 9:28
 * @projectName CoffeeLoverSupportLibrary
 * @className ShareActivity.java
 * @description TODO
 * todo bugs  Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
 * todo easyphoto 最新版本 3.0 根据主题调整图片选择框架的相应主题 需要 当前活动有主题
 * todo ShareActivity 继承自 BaseActivity 所以堆栈信息报到了 BaseActivity
 * todo 解决方案 为 该 Activity  设置相应主题
 *
 * todo:图片未能显示的真正原因 可能是
 *todo 从Android10开始，引入了分区存储，不让直接通过File的方式操作SD卡路径了。必须通过MediaStore，也就是说，让MediaStore给你指定存放位置，暴露抽象的Uri，让你用，真实路径隐藏。
 * 也就是说：当前所使用的模拟器 是android 8.0 版本未引入 分区存储
 * getBinding().gridViewAdd.setAdapter(new NineGridViewClickAdapter(getContext(),imageInfos));
 * 九宫格加载图片也好 图片选择框架加载图片也好 都是使用文件路径 包括后续文件上传都可以直接操作文件路径 加载图片 生成File 对象
 *
 * 而真机版本 往往 大于 10.0 的不能在直接通过该种方式处理了 中间要经过 MediaStore 转手--真实路径隐藏
 *
 */
public class ShareActivity extends BaseActivity<ShareViewModel, ShareActivityBinding> implements
        View.OnClickListener,View.OnFocusChangeListener{

    // TODO: 2021/11/27  aliyun API 上传图片
    private OSSClient client;
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";

    //初始时 EditText 相对 NineGridView 布局参数值（px）--待做兼容性处理
    private static final int BASE_TITLE_MARGIN=450;
    private static final int BASE_CONTENT_MARGIN=500;
    private RelativeLayout.LayoutParams titleParam;
    private RelativeLayout.LayoutParams contentParam;
    // 避免初次进入时监听到焦点改变自动上滑
    private int flag=0;
    private StartSelectListener selectListener;
    private SelectCallbackListener selectCallbackListener;
    private  MyDialog dialog;
    // TODO: 2021/11/28 控制风扇


    @Override
    public void registerUIChangeCallBack() {

        getViewModel().getSelectPicture()
                .observe(this, new Observer<List<ImageInfo>>() {
                    @Override
                    public void onChanged(List<ImageInfo> imageInfos) {
                        // TODO: 2021/11/26 创建适配器 对布局参数动态调整 处理 addMore 控件的可见性
                        if(null!=imageInfos){
                            uiLayoutChangeFunction(imageInfos.size());
                            getBinding().gridViewAdd.setAdapter(new NineGridViewClickAdapter(getContext(),imageInfos));
                        }
                    }
                });

        getViewModel().getDialogEvent().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if(s.equals("uploadFailure!")){
                     dialog.dismiss();
                     Toast.makeText(getContext(),"load image Failure,please check your network!",Toast.LENGTH_SHORT).show();
                }else if(s.equals("shareFailure!")){
                    dialog.dismiss();
                    Toast.makeText(getContext(),"share Failure,please check your network!",Toast.LENGTH_SHORT).show();
                }else if(s.equals("shareSuccess!")){
                    dialog.dismiss();
                    Toast.makeText(getContext(),"分享成功即将跳转",Toast.LENGTH_SHORT).show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(2000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ShareActivity.this.finish();
                                }
                            });
                        }
                    }).start();
                }
            }
        });

    }
    @Override
    public int getLayoutId() {
        return R.layout.share_activity;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        // TODO: 2021/11/27   初始化 aliyun 文件直传 API
        // UpLoadFile.asyUpLoad(file,client);   ViewModel层 处理

        // TODO: 2021/11/28   准备 Dialog
        dialog=new MyDialog(getContext());
        dialog.setView();
        dialog.setCancelable(false);


        OSSCredentialProvider credentialProvider =
                new OSSPlainTextAKSKCredentialProvider("LTAI5tNgkcpfK7wNL7MXgkvG" ,
                        "iocrZUFJv2Nq7wbhvFvJ6WgusRAcSB");
        client=new OSSClient(getApplicationContext(), ENDPOINT, credentialProvider);

        selectListener=new StartSelectListener();
        selectCallbackListener=new SelectCallbackListener();

        getBinding().addShareTitle.setOnClickListener(this);
        getBinding().addShareTitle.setOnFocusChangeListener(this);
        getBinding().shareContent.setOnClickListener(this);
        getBinding().shareContent.setOnFocusChangeListener(this);
        getBinding().addMorePicture.setVisibility(View.INVISIBLE);
        titleParam=(RelativeLayout.LayoutParams) getBinding().addShareTitle.getLayoutParams();
        contentParam=(RelativeLayout.LayoutParams)getBinding().shareContent.getLayoutParams();
        getBinding().sharePhoto.setOnClickListener(selectListener);
        getBinding().addMorePicture.setOnClickListener(selectListener);
        getBinding().shareLocation.setOnClickListener(this);
        getBinding().sharePublish.setOnClickListener(this);
        getBinding().gridViewAdd.setSingleImageSize(200);
        getBinding().gridViewAdd.setSingleImageRatio((float) 1.0);
        getBinding().shareHelp.setOnClickListener(this);
        //九宫格图片加载引擎
        NineGridView.setImageLoader(new ShareActivity.GlideImageLoader());

    }

    // TODO: 2021/11/26   对 EditTextView 焦点事件  点击事件监听 处理自动指定编辑时自动调整编辑框位置

    /**
    * @date 2021/11/26 14:45
    * @params [requestCode, resultCode, data]
    * @return void
    * @description TODO 通过相应编码判断处理了类型 拿到选择图片的路径数组
     *   getViewModel().clearSelectPicture();
     *   getViewModel().providerData(resultPaths);
     *   todo: 撤销重写  onactivityresult 采用链式回调处理图片选择结果
    */



    /**
    * @date 2021/11/26 14:46
    * @params
    * @return
    * @description TODO 对布局参数进行动态处理 动态适应布局
    */
    private void uiLayoutChangeFunction(@NonNull int size){
        //clear 校准450 500  320 370
        //附加功能-- 设置addMore 的可见性或者不可见行
        titleParam.topMargin=BASE_TITLE_MARGIN;
        contentParam.topMargin=BASE_CONTENT_MARGIN;
        if(size<=0){
            titleParam.topMargin+=90;
            contentParam.topMargin+=110;
            getBinding().addMorePicture.setVisibility(View.INVISIBLE);
        }else{
            // nine 扩展后的 布局微调
            titleParam.topMargin-=180;
            contentParam.topMargin-=160;
            getBinding().addMorePicture.setVisibility(View.VISIBLE);
        }
        getBinding().addShareTitle.setLayoutParams(titleParam);
        getBinding().shareContent.setLayoutParams(contentParam);
    }


    /**
    * @date 2021/11/26 14:54
    * @params [v]
    * @return void
    * @description TODO  点击监听  焦点改变监听 联合处理编辑框自动滚动效果  其他控件的处理逻辑
    */
    @Override
    public void onClick(View v) {
        if(v==getBinding().addShareTitle){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
        }else if(v==getBinding().shareContent){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
        }else if(v==getBinding().shareCancel){
              ShareActivity.this.finish();
        }else if(v==getBinding().shareSave){

        }else if(v==getBinding().shareHelp){

        }else if(v==getBinding().sharePublish){
            dialog.run();
            dialog.show();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // TODO: 2021/11/28  展示对话框效果
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    getViewModel().uploadImage(getBinding().addShareTitle.getText().toString(),
                            getBinding().shareContent.getText().toString(),client);

                }
            }).start();

//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//                        Thread.sleep(5000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(getContext(),"开始调用",Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//            }).start();
//
//
//
//            getViewModel().uploadImage(getBinding().addShareTitle.getText().toString(),
//                     getBinding().shareContent.getText().toString(),client);

        }else if(v==getBinding().shareAddWater){

        }else if (v==getBinding().shareLocation){
            startActivity(LocationServiceActivity.class);
        }
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(flag!=0){
            getBinding().shareScroll.scrollTo(0,getBinding().addShareTitle.getTop()-getBinding().position.getHeight()-40);
            flag++;
        }
    }

    /**
    * @date 2021/11/26 14:42
    * @params
    * @return
    * @description TODO  九宫格控件图片加载引擎
    */
    private class GlideImageLoader implements NineGridView.ImageLoader{

        @Override
        public void onDisplayImage(Context context, ImageView imageView, String uri) {
            Glide.with(context).load(uri).into(imageView);
        }
        @Override
        public Bitmap getCacheImage(String uri) {
            return null;
        }
    }

    /**
    * @date 2021/11/26 15:51
    * @params
    * @return
    * @description TODO 选择分享图片的监听器
     *
     * // TODO: 2021/11/28  easyphoto 3.0 版本  不再使用 onActivityResult
     * todo：new SelectCallback()   替代
     * todo  setSelectedPhotos(ArrayList<Photo> selectedPhotos)  设置默认选中的图片 使用Photo 而非 String path
    *
    * getViewModel().clearSelectPicture();
    * getViewModel().providerData(resultPaths);
    */
    class StartSelectListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(v==getBinding().sharePhoto){
                EasyPhotos.createAlbum((Activity) getContext(), true,true, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.fileprovider")
                        .setPuzzleMenu(true)
                        .setCount(9)
                        .start(selectCallbackListener);
           // reversionDataList(getViewModel().getSelectPicture().getValue()
            }else if(v==getBinding().addMorePicture){
                EasyPhotos.createAlbum((Activity) getContext(), true,true, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.coffeeloversupportlibrary.coffeelover.domain.dailyshare.fileprovider")
                        .setPuzzleMenu(true)
                        .setCount(9)
                        .setSelectedPhotoPaths(reversionDataList(getViewModel().getSelectPicture().getValue()))
                        .start(selectCallbackListener);
            }
        }
    }
    class SelectCallbackListener extends SelectCallback{
        @Override
        public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
            getViewModel().providerData(photos);
        }

        @Override
        public void onCancel() {
            if(null!=getViewModel().getSelectPicture().getValue()){
                if(getViewModel().getSelectPicture().getValue().size()>0){
                    getViewModel().clearSelectPicture();
                }
            }
        }
    }
    /**
    * @date 2021/11/26 16:17
    * @params [source]
    * @return java.util.List<java.lang.String>
    * @description TODO  逆转数据 ImageInfo -- Photo
    */
    private ArrayList<String> reversionDataList(List<ImageInfo> source){
        ArrayList<String> target=new ArrayList<String>();
        for(ImageInfo info:source){
            target.add(info.getThumbnailUrl());
        }
        return target;
    }
}
